<!-- 上传组件 -->
<template class="upload">
  <el-upload
    action="http://localhost:3000/upload/"
    list-type="picture-card"
    :on-success="handleSuccess"
    :on-remove="handleRemove"
    :class="{stleA: fileList === 0,  stleB: fileList === 1}">
     <img :src="imgUrl" alt="">
     <i class="el-icon-plus"></i>
  </el-upload>
</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs, watch } from 'vue';
import { useStore } from 'vuex'

export default defineComponent ({
  name: 'Upload',
  props: [ 'icon', 'index' ],
  setup (props, ctx) {
    const content = reactive({
      store: useStore(),
      fileList: 0,
      imgUrl: '',
    })

    watch(() => props.icon, (val) => {
      content.imgUrl = val;
    }, { immediate: true, deep: true })

    // 上传成功触发
    function handleSuccess(response: any) {
      const url = response.data[0].url;
      content.fileList = 1;
      // 传递图片的 url 给父组件
      ctx.emit('uploadUrl', [url, props.index]);
    }

    // 删除图片触发
    function handleRemove() {
      console.log('删除图片');
      content.fileList = 0;
    }

    const refContent = toRefs(content);

      return {
      ...refContent,
      handleSuccess,
      handleRemove
    }
  }
})
</script>

<style lang='scss' scoped>
.el-upload {
  img {
    width: 100%;
  }
  // + 号图标，定位居中
  .el-icon-plus {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>